package wang.lxl.concurrent.lockTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程按序交替运行
 */
public class ThreadLoopExe {
    public static void main(String[] args) {
        final ThreadLoop tl = new ThreadLoop();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                tl.loopA(i);
            }
        },"A").start();
        new Thread(() ->{
                for (int i = 1; i <= 10; i++) {
                    tl.loopB(i);
                }
            },"B").start();
        new Thread(()->{
            for (int i = 1; i <= 10; i++) {
                tl.loopC(i);
            }
        },"C").start();
    }
}
class ThreadLoop{
    private int threadNo=1;// 记录线程编号
    private Lock lock = new ReentrantLock();
    private Condition con1 = lock.newCondition();
    private Condition con2 = lock.newCondition();
    private Condition con3 = lock.newCondition();

    /**
     * 循环A
     * @param loopCount 循环的轮数
     */
    public void loopA(int loopCount){
        lock.lock();
        try {
            if (threadNo !=1) {
                con1.await();// 等待
            }
            for (int i = 1; i < 2; i++) {
                System.out.println(Thread.currentThread().getName() +"\t"+i+"\t"+loopCount);
            }
            threadNo =2;
            con2.signal();// 唤醒2号线程
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
            lock.unlock();
        }
    }

    /**
     * B循环
     */
    public void loopB(int loopCount){
        lock.lock();
        try {
            if (threadNo != 2) {
                con2.await();// 等待
            }
            for (int i = 1; i < 2; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+loopCount);
            }
            threadNo=3;
            con3.signal();// 唤醒3号线程
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
            lock.unlock();
        }
    }

    public void loopC(int loopCount) {
        lock.lock();
        try {
            if (threadNo !=3) {
                con3.await();
            }
            for (int i = 1; i < 2; i++) {
                System.out.println(Thread.currentThread().getName()+"\t"+i+"\t"+loopCount);
            }
            System.out.println("-------------第 "+loopCount+" 轮循环结束----------------");
            threadNo=1;
            con1.signal();// 唤醒1号线程
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }finally {
            lock.unlock();
        }
    }
}
